// pages/fb_chatRooms/fb_chatRooms.js
import tool from '../../modules/tool'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: [],
    handleUser: []
  },

  handleOpenChatRoom(e) {
    e = e.currentTarget.dataset
    console.log(e)
    tool.chatRoom.showChatRoomPage(e.id, e.ishandleuser)
  },

  handleBack() {
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    tool.setPageData(this)
    let data = tool.store.getItem('chatRoomListData')
    tool.store.removeItem('chatRoomListData')
    if (data) {
      console.log(data)
      this.setData(data)
    } else {
      wx.navigateBack()
      return
    }
    const myOpenId = tool.store.getItem('openId')
    const myUserId = tool.store.getItem('userData')?.id
    tool.store.onChange('newChatRoom', e => {
      if (e.userOpenId == myOpenId) {
        this.setData({
          user: tool.appendChatRoomItem(this.data.user, e)
        })
      }
      if (myUserId === e.handleUserId) {
        this.setData({
          handleUser: tool.appendChatRoomItem(this.data.handleUser, e)
        })
      }
    })
    tool.store.onChange('chatMessage', async e => {
      try {
        let re = await tool.requestData('/chatRoom/getChatRoomList', {
          openId: tool.store.getItem('openId'),
          userId: !tool.store.getItem('userData')?.id ? undefined : tool.store.getItem('userData')?.id
        }, 'get', false)
        if(re.status){
          for(let i=0;i<re.data.length;i++){
            if(re.data[i].chatRoomId===e.id){
              re.data[i].userUnread++
              re.data[i].handleUserUnread++
            }
          }
          this.setData(re.data)
        }
      } catch (error) {

      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})